/*
  学习目标：输入存入redux
  步骤：
     0. 声明状态，定义状态的类型
     1. actionType
     2. 编写保存的逻辑
     3. dispatch
*/

const initialState = {
  articles: {} as ArticleStateType,
  detail: {} as ArticleDetailType,
};

type ArticleActionType =
  | {
      type: 'article/saveList';
      payload: { results: ArticleType[]; pre_timestamp: number; channel_id: number };
    }
  | {
      type: 'article/udpateListById';
      payload: { results: ArticleType[]; pre_timestamp: number; channel_id: number };
    }
  // 1.
  | { type: 'article/saveDetail'; payload: ArticleDetailType };

export default function articleReducer(
  state = initialState,
  action: ArticleActionType
): typeof initialState {
  switch (action.type) {
    case 'article/saveList':
      const { channel_id, pre_timestamp, results } = action.payload;
      return {
        ...state,
        articles: {
          ...state.articles,
          [channel_id]: {
            pre_timestamp,
            results,
          },
        },
      };
    case 'article/udpateListById':
      const {
        channel_id: update_id,
        pre_timestamp: udpate_timestamp,
        results: update_results,
      } = action.payload;
      const oldResultsById = state.articles[update_id]?.results || [];
      const newResultsById = [...oldResultsById, ...update_results];
      return {
        ...state,
        articles: {
          ...state.articles,
          [update_id]: {
            results: newResultsById,
            pre_timestamp: udpate_timestamp,
          },
        },
      };
    // 2.
    case 'article/saveDetail':
      return {
        ...state,
        detail: {
          ...action.payload,
        },
      };

    default:
      return state;
  }
}

export type ArticleType = {
  art_id: string;
  title: string;
  aut_id: string;
  comm_count: number;
  pubdate: string;
  aut_name: string;
  is_top: number;
  cover: {
    type: number;
    images: string[];
  };
};
type ArticleStateType = {
  [channelId: number]: {
    results: ArticleType[];
    pre_timestamp: number;
  };
};

/** 文章详情的类型 */
export type ArticleDetailType = {
  art_id: string;
  title: string;
  pubdate: string;
  aut_id: string;
  content: string;
  aut_name: string;
  aut_photo: string;
  is_followed: boolean;
  is_collected: boolean;
  attitude: number;
  comm_count: number;
  read_count: number;
  like_count: number;
};
